package org.replay.config;

/*
 * Copyright © 2020 lizicong,All rights reserved.
 *
 * Licensed under the GPL License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * RabbitMQ连接信息
 * @author lizicong
 */
@Configuration
public class RabbitConnectionConfiguration implements BeanPostProcessor {


    @Bean("rabbitConnectionConfiguration-cfg")
    public JSONObject cfg(@Qualifier("nacos-cfg") JSONObject nacosConfiguration) {
        //截取相应的JSON配置信息中的节点
        return nacosConfiguration.getJSONObject("RabbitMQ");
    }

    @Resource
    @Qualifier("rabbitConnectionConfiguration-cfg")
    JSONObject cfg;


    /**
     * RabbitMQ连接信息
     * 在工程启动时截取启动时修改RabbitMQ连接信息配置信息类以覆盖自定义配置信息
     *
     * @param object 所有springboot自动注册的bean集
     * @param name   我也不知道是啥
     * @return null
     */
    @Override
    public Object postProcessAfterInitialization(Object object, String name) {
        if (object instanceof RabbitProperties) {
            RabbitProperties rabbitProperties = (RabbitProperties) object;
            rabbitProperties.setHost(cfg.getString("HOST"));
            rabbitProperties.setPort(Integer.valueOf(cfg.get("PORT").toString()));
            rabbitProperties.setUsername(cfg.getString("USERNAME"));
            rabbitProperties.setPassword(cfg.getString("PASSWORD"));
            rabbitProperties.setPublisherReturns(true);
            rabbitProperties.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        }
        return null;
    }
}
